package com.whpost.api.controller.stamp.h5;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.whpost.api.entity.ReqLogin;
import com.whpost.api.utils.ApiUtils;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.addr.TWxAddrDao;
import com.whpost.service.dao.t.TCzyDao;
import com.whpost.service.dao.t.THyxxDao;
import com.whpost.service.dao.t.TWxInfoDao;
import com.whpost.service.entity.addr.TWxCity;
import com.whpost.service.entity.addr.TWxCounty;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.THyxx;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.entity.wx.TWxInfo;
import com.whpost.service.service.stamp.h5.JsApi;
import com.whpost.service.service.stamp.h5.StampH5Services;
import com.whpost.service.service.stamp.h5.WxTokenServiceImpl;
import com.whpost.service.service.t.TApiNonceH5Service;
import com.whpost.service.tools.Aes;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stamp/h5/api")
public class ApiController {

    @Resource
    private THyxxDao tHyxxDao;
    @Resource
    private StampH5Services stampH5Services;
    @Resource
    private TApiNonceH5Service tApiNonceH5Service;
    @Resource
    private TWxAddrDao tWxAddrDao;
    @Resource
    private Wdpz wdpz;
    @Resource
    private WxTokenServiceImpl wxTokenService;
    @Resource
    private TWxInfoDao tWxInfoDao;
    @Resource
    private JsApi jsApi;
    /**
     *
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    @RequestMapping(value ="login")
    public ResultInfo login(@RequestBody Map<String, Object> map) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException {

        ToolBean.info("map:"+map.get("map"));
        String backurl = (String)map.get("backurl");
        ToolBean.info("backurl:"+backurl);
        String redirect_uri = wdpz.getYm()+"h5/login_do?backUrl="+java.net.URLEncoder.encode(backurl,"utf-8")+"";
        ToolBean.info("redirect_uri:"+redirect_uri);
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc363f1f58277ae1f&redirect_uri="+java.net.URLEncoder.encode(redirect_uri,"utf-8")+"&response_type=code&scope=snsapi_userinfo&state=12#wechat_redirect";
        ToolBean.info("url:"+url);
        return new ResultInfo(0, "获取地址成功！",url);
    }

    @RequestMapping(value ="login_do_wx")
    public ResultInfo loginWx(@RequestBody Map<String, Object> map) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException {

        ToolBean.info("map:"+map.get("map"));
        String code = (String)map.get("code");
        String backurl = (String)map.get("backurl");
        String state = (String)map.get("state");
        ToolBean.info("微信授权换取到的code:"+code);
        THyxx tHyxx = new THyxx();
        TWxInfo tWxInfo =tWxInfoDao.selectById("1");
        tHyxx = wxTokenService.getOpenidByCode(tWxInfo.getAppid(),tWxInfo.getAppsecret(),code);
        if (null == tHyxx) {
            return new ResultInfo(500, "没有获取会员信息，登录失败！",null);
        }
        //如果用户没有秘钥，补充秘钥
        if (StringUtils.isEmpty(tHyxx.getAeskey()) || StringUtils.isEmpty(tHyxx.getAesiv())){
            tHyxx.setAeskey(ToolBean.getRandomString(16));
            tHyxx.setAesiv("0102030405060708");
            tHyxxDao.updateById(tHyxx);
        }
        //校验完，准备登录，浏览器关闭后，token失效
        StpUtil.login(tHyxx.getLsh(),"h5");
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        String token = tokenInfo.getTokenValue();
        String data = "{\"code\":\"200\",\"token_h5\":\"" + token + "\",\"a_h5\":\"" + tHyxx.getAeskey() + "\",\"b_h5\":\"" + tHyxx.getAesiv() + "\",\"c_h5\":\"" + tHyxx.getLsh() + "\"}";
        ToolBean.info("登录成功，准备加密后返回的字符串:"+data);
        String rtnStr = Aes.encrypt(data,"NLfZ3aIOg77E2rT8");
        return new ResultInfo(0, "登录成功！",rtnStr);
    }

    @RequestMapping(value ="login_test")
    public ResultInfo loginTest() throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {

        THyxx tHyxx =tHyxxDao.selectById(3);
        //校验完，准备登录，浏览器关闭后，token失效
        StpUtil.login(tHyxx.getLsh(),"h5");
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        String token = tokenInfo.getTokenValue();
        String data = "{\"code\":\"200\",\"token_h5\":\"" + token + "\",\"a_h5\":\"" + tHyxx.getAeskey() + "\",\"b_h5\":\"" + tHyxx.getAesiv() + "\",\"c_h5\":\"" + tHyxx.getLsh() + "\"}";
        ToolBean.info("登录成功，准备加密后返回的字符串:"+data);
        String rtnStr = Aes.encrypt(data,"NLfZ3aIOg77E2rT8");
        return new ResultInfo(0, "登录成功！",rtnStr);
    }

    /**
     *
     * @return
     */
    @SaCheckLogin
    @RequestMapping(value ="/check_login")
    @ResponseBody
    public ResultInfo checkLogin(HttpServletRequest httpServletRequest,@RequestBody Map<String, Object> map) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
        String loginId = ApiUtils.getLoginId();
        ToolBean.info("获取到的用户id:"+loginId);
        ToolBean.info("获取到的map:"+map.get("dz"));
        //返回微信相关
        //wxJS
        TWxInfo tWxInfo = tWxInfoDao.selectById("1");
        String timestamp= ToolBean.getTodayStr("yyyyMMddHHmmss");
        String nonceStr = ToolBean.getRandomString(16);
        String url = (String)map.get("dz");
        ToolBean.info("wxjs发起页面："+url);
        String ticket = jsApi.GetApiTicket(tWxInfo.getAppid(),tWxInfo.getAppsecret(),tWxInfo.getLsh());
        String signature = jsApi.GetJsSignature(nonceStr,timestamp,url,ticket);
        String data = "{\"code\":\"200\",\"timestamp\":\"" +timestamp+ "\",\"nonceStr\":\"" +nonceStr+ "\",\"signature\":\"" +signature+ "\",\"appid\":\"" +tWxInfo.getAppid()+ "\"}";
        return new ResultInfo(200, "服务正常！",data);
    }

    /**
     * 获取活动
     * @return
     */
    @RequestMapping(value ="/get_hd")
    public ResultInfo getHd(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getHd(loginId,map);
    }

    /**
     * 获取活动相关模版
     * @return
     */
    @RequestMapping(value ="/get_hd_mb")
    public ResultInfo getHdMb(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getHdMb(loginId,map);
    }

    /**
     * 获取活动相关模版
     * @return
     */
    @RequestMapping(value ="/get_hd_mb_gxh")
    public ResultInfo getHdGxhMb(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getHdGxhMb(loginId,map);
    }

    /**
     * 明信片确认图案
     * @param imgDate
     * @param lx
     * @param stmbid
     * @param htmbid
     * @param hdid
     * @return
     */
    @PostMapping(value = "/qrta")
    @ResponseBody
    public String qrta(String imgDate, String lx, String stmbid, String htmbid, String hdid) {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.qrta(loginId,imgDate,lx,stmbid,htmbid,hdid);
    }

    /**
     * 个性化邮票1
     * @param hdid
     * @return
     */
    @PostMapping(value = "/gxh_tp1")
    @ResponseBody
    public String gxh_tp1(String imgDate1,String hdid) {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.gxhTp1(loginId,imgDate1,hdid);
    }

    /**
     * 个性化邮票2
     * @return
     */
    @PostMapping(value = "/gxh_tp2")
    @ResponseBody
    public String gxh_tp2(String imgDate2,String card_id) {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.gxhTp2(loginId,imgDate2,card_id);
    }

    /**
     * 个性化邮票确认图案
     * @return
     */
    @PostMapping(value = "/qrta1")
    @ResponseBody
    public String qrta1(String card_id) {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.qrta1(loginId,card_id);
    }

    /**
     * 显示我的照片，暂时没有分页
     * @param map
     * @return
     */

    @PostMapping(value = "/get_wdzp")
    public ResultInfo getWdzp(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getWdzp(loginId,map);
    }

    /**
     * 显示我的照片，暂时没有分页
     * @param map
     * @return
     */

    @PostMapping(value = "/wdzp_del")
    public ResultInfo wdzpDel(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.wdzpDel(loginId,map);
    }

    /**
     * 获取nonce
     * @param map
     * @return
     */
    @RequestMapping("/getnonce")
    @ResponseBody
    public ResultInfo getNonce(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return tApiNonceH5Service.getNonce(loginId,map);
    }

    /**
     * 生成订单
     * @param map
     * @return
     */
    @RequestMapping("/create_order")
    @ResponseBody
    public ResultInfo createOrder(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.createOrder(loginId,map);
    }

    /**
     * 显示订单详情
     * @param map
     * @return
     */
    @RequestMapping("/order_info")
    @ResponseBody
    public ResultInfo orderInfo(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.orderInfo(loginId,map);
    }

    /**
     * 订单确认
     * @param map
     * @return
     */
    @RequestMapping("/order_qr")
    @ResponseBody
    public ResultInfo orderQr(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.orderQr(loginId,map);
    }

    /**
     * 付款信息
     * @param map
     * @return
     */
    @RequestMapping("/pay_info")
    @ResponseBody
    public ResultInfo payInfo(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.payInfo(loginId,map);
    }

    /**
     * 获取付款payid
     * @param map
     * @return
     */
    @RequestMapping("/getpayid")
    @ResponseBody
    public ResultInfo getPayId(@RequestBody Map<String, Object> map, HttpServletRequest httpServletRequest) throws ParseException {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getPayId(loginId,map,httpServletRequest);
    }
    /**
     * 兑换码逻辑
     * @param map
     * @return
     */
    @RequestMapping("/getpayid_dhm")
    @ResponseBody
    public ResultInfo getPayIdDhm(@RequestBody Map<String, Object> map, HttpServletRequest httpServletRequest) throws ParseException {
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.getPayIdDhm(loginId,map,httpServletRequest);
    }

    /**
     * 地址查询
     * @param map
     * @return
     */
    @RequestMapping("/addr_query")
    @ResponseBody
    public ResultInfo addrQuery(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.addrQuery(loginId,map);
    }

    /**
     * 地址保存
     * @param map
     * @return
     */
    @RequestMapping("/addr_save")
    @ResponseBody
    public ResultInfo addrSave(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.addrSave(loginId,map);
    }

    /**
     * 地址默认设置
     * @return
     */
    @RequestMapping("/addr_default")
    @ResponseBody
    public String addrDefault(String lx,String id,String token){
        String loginId  = (String)StpUtil.getLoginIdByToken(token);
        return stampH5Services.addrDefault(loginId,id,lx);
    }

    /**
     * 获取区域选择
     * @param map
     * @return
     */
    @RequestMapping("/addr_area")
    @ResponseBody
    public ResultInfo addrArea(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.addrArea(loginId,map);
    }

    /**
     * 根据省份获取城市
     * @return
     */
    @RequestMapping(value ="/getcity",method = RequestMethod.POST)
    @ResponseBody
    public String getCity(String province_id,String city_id,String token) {
        String loginId  = (String)StpUtil.getLoginIdByToken(token);
        if (StringUtils.isEmpty(loginId)) {
            return null;
        }
        String htmlStr="";
        List<TWxCity> tWxCityL= null;

        try{
            tWxCityL = tWxAddrDao.getCityLByProv(province_id);
            if (tWxCityL.size()==0)
            {
                htmlStr = "error|没有可加载的新数据";
                return htmlStr;
            }
            else {
                for (int i = 0; i < tWxCityL.size(); i++) {
                    /*String l = String.valueOf(tWxCityL.get(i).getLsh());
                    if (city_id.equals(l))
                        htmlStr += "<div id=\"div_c_"+tWxCityL.get(i).getLsh()+"\" onclick=\"set_city('"+tWxCityL.get(i).getLsh()+"','"+tWxCityL.get(i).getName()+"','"+tWxCityL.get(i).getCityId()+"');\">"+tWxCityL.get(i).getName()+"<span class=\"img-span\"><img src=\""+basePath+"/image/ico/tick.png\" width=\"16px\"></span></div>";
                    else*/
                    htmlStr += "<div id=\"div_c_"+tWxCityL.get(i).getLsh()+"\" onclick=\"set_city('"+tWxCityL.get(i).getLsh()+"','"+tWxCityL.get(i).getName()+"','"+tWxCityL.get(i).getCityId()+"');\">"+tWxCityL.get(i).getName()+"</div>";
                }
                htmlStr = "success|" + htmlStr;
            }
            return htmlStr;

        }catch (Exception e)
        {
            htmlStr = "error|"+e.getMessage();
            ToolBean.info("获取城市错误："+e.getMessage());
            return htmlStr;
        }
    }

    /**
     * 根据城市获取县区
     * @return
     */
    @RequestMapping(value ="/getcounty",method = RequestMethod.POST)
    @ResponseBody
    public String getCounty(String city_id,String county_id,String token) {
        String loginId  = (String)StpUtil.getLoginIdByToken(token);
        if (StringUtils.isEmpty(loginId)) {
            return null;
        }
        String htmlStr="";
        List<TWxCounty> tWxCountyL= null;
        try{
            tWxCountyL = tWxAddrDao.getCountyLByCity(city_id);
            if (tWxCountyL.size()==0)
            {
                htmlStr = "error|没有可加载的新数据";
                return htmlStr;
            }
            else {
                for (int i = 0; i < tWxCountyL.size(); i++) {
                   /* String l = String.valueOf(tWxCountyL.get(i).getLsh());
                    String str="";
                    if (county_id.equals(l)) str="<span class=\"img-span\"><img src=\""+basePath+"/image/ico/tick.png\" width=\"16px\"></span>";
                    else str="";*/
                    htmlStr += "<div id=\"div_county_"+tWxCountyL.get(i).getLsh()+"\" onclick=\"set_county('"+tWxCountyL.get(i).getLsh()+"','"+tWxCountyL.get(i).getName()+"','"+tWxCountyL.get(i).getCountyId()+"');\">"+tWxCountyL.get(i).getName()+"</div>";
                }
                htmlStr = "success|" + htmlStr;
            }
            return htmlStr;

        }catch (Exception e)
        {
            htmlStr = "error|"+e.getMessage();
            ToolBean.info("获取县区错误："+e.getMessage());
            return htmlStr;
        }
    }

    /**
     * 我的订单查询
     * @param map
     * @return
     */
    @RequestMapping("/myorder_query")
    @ResponseBody
    public ResultInfo myorderQuery(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.myorderQuery(loginId,map);
    }

    /**
     * 我的订单查询
     * @param map
     * @return
     */
    @RequestMapping("/myorder_del")
    @ResponseBody
    public String myorderDel(@RequestBody Map<String, Object> map){
        String loginId = ApiUtils.getLoginId();
        return stampH5Services.myorderDel(loginId,map);
    }

    /**
     * 模拟参数：<script>alert("xss");</script>
     */
    @GetMapping("/xss")
    public String xss(String data) {
        System.out.println(data);
        return data;
    }

    @RequestMapping(value ="getsp")
    public ResultInfo getsp(@RequestBody Map<String, Object> map)  {

        ToolBean.info("map:"+map.get("map"));
        return new ResultInfo(0, "获取地址成功！",null);
    }
}
